package com.xcm.sso;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xcm.cache.RedisCacheDao;
import com.xcm.constant.*;
import com.xcm.model.SysAuthority;
import com.xcm.model.SysUser;
import com.xcm.model.response.JsonResponseBuilder;
import com.xcm.model.vo.SysUserVo;
import com.xcm.service.SysAuthorityService;
import com.xcm.service.SysUserService;
import com.xcm.util.*;
import com.xcm.util.captcha.CaptchaHelper;
import com.xcm.validator.SysUserValidator;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

/**
 * 登录和注销控制器
 *
 * @author 林强
 * @date 2018-04-12 11:15
 */
@Controller
public class SSOLoginController {
    private static Logger logger = LoggerFactory.getLogger(SSOLoginController.class);

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysAuthorityService sysAuthorityService;
    @Autowired
    private RedisCacheDao redisCacheDao;
    @Autowired
    private SSOProperties ssoProperties;

    /**
     * 预登录
     */
    @RequestMapping(value = "/preLogin")
    public String preLogin(HttpServletRequest request, HttpServletResponse response, Model model) {
        String loginPage = SSOContants.PATH.LOGIN_PAGE_PORTAL.getValue();
        try {
            //目的地址
            String gotoURL = request.getParameter(SSOContants.REDIRECT_URL);
            //设置cookie地址
            String setCookieURL = request.getParameter(SSOContants.SET_COOKIE_URL);
            //系统标志
            String platformTag = request.getParameter(SSOContants.PLATFORM_TAG);
            List<SysAuthority> systemList = sysAuthorityService.listSystem();
            if (CollectionUtils.isEmpty(systemList)) {
                model.addAttribute(BaseConstant.MSG, SSOContants.MSG_NO_SYSTEM);
                return SSOContants.PATH.PAGE_401.getValue();
            }
            if (StringUtils.isBlank(platformTag)) {
                platformTag = ssoProperties.getSystemSignPortal();
            } else {
                boolean isSystemRight = false;
                for (SysAuthority aSystemList : systemList) {
                    if (aSystemList.getSign().equals(platformTag)) {
                        isSystemRight = true;
                        break;
                    }
                }
                if (!isSystemRight) {
                    model.addAttribute(BaseConstant.MSG, SSOContants.MSG_SYSTEM_SIGN_ERROR);
                    return SSOContants.PATH.PAGE_401.getValue();
                }
            }
            loginPage = SSOUtils.getSystemLoginPageBySystem(ssoProperties, platformTag);
            if (StringUtils.isBlank(gotoURL)) {
                model.addAttribute(BaseConstant.MSG, SSOContants.MSG_GOTO_URL_ERROR);
                return SSOContants.PATH.PAGE_401.getValue();
            }
            model.addAttribute(SSOContants.REDIRECT_URL, gotoURL);
            model.addAttribute(SSOContants.SET_COOKIE_URL, setCookieURL);
            model.addAttribute(SSOContants.PLATFORM_TAG, platformTag);
            //验证cookie是否存在
            Cookie ticketCookie = CookieUtils.getCookieByName(request, CookieConstant.WHOLE_COOKIE_NAME);
            if (null == ticketCookie) {
                return loginPage;
            }
            //验证ticket是否存在
            String encodedTicket = ticketCookie.getValue();
            String decodedTicket = DESUtils.decrypt(encodedTicket, ssoProperties.getSecretKey());
            if (!redisCacheDao.hasKey(ssoProperties.getSsoTicketsCacheName(), decodedTicket)) {
                model.addAttribute(BaseConstant.MSG, SSOContants.MSG_TICKET_NOT_EXITS);
                return loginPage;
            }
            //验证ticket是否过期
            boolean isTicketExpire = SSOUtils.isTicketExpire(redisCacheDao, decodedTicket, ssoProperties);
            if (isTicketExpire) {
                model.addAttribute(BaseConstant.MSG, SSOContants.MSG_TICKET_EXPIRE);
                return loginPage;
            }
            String portalRedirectURL = DESUtils.decrypt(gotoURL, ssoProperties.getSecretKey());
            //统一账户管理系统已登录
            if (ssoProperties.getSystemSignPortal().equals(platformTag)) {
                return "redirect:" + portalRedirectURL;
            }
            // 其他系统已登录
            String setCookieURLDecoded = DESUtils.decrypt(setCookieURL, ssoProperties.getSecretKey());
            String newRedirectURL = setCookieURLDecoded + "?gotoURL=" + gotoURL + "&ticket=" + encodedTicket + "&expiry=" + ticketCookie.getMaxAge();
            response.sendRedirect(newRedirectURL);
        } catch (Exception e) {
            logger.error("SSOLoginController preLogin SSO预登录失败：" + e.getMessage());
        }
        return loginPage;
    }

    /**
     * 验证是否登录
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/authTicket")
    public Object authTicket(HttpServletRequest request) {
        String encodedTicket = request.getParameter(SSOContants.TICKET);
        try {
            if (encodedTicket == null) {
                return JsonResponseBuilder.buildFail(SSOContants.MSG_NO_TICKET);
            }
            String decodedTicket = DESUtils.decrypt(encodedTicket, ssoProperties.getSecretKey());
            if (redisCacheDao.hasKey(ssoProperties.getSsoTicketsCacheName(), decodedTicket)) {
                // TODO 检查ticket是否过期
                Object ticketObj = redisCacheDao.getCache(ssoProperties.getSsoTicketsCacheName(), decodedTicket);
                if (null == ticketObj) {
                    return JsonResponseBuilder.buildFail(SysUserConstants.NOT_LOGIN_OR_EXPIRE);
                }
                JSONObject ticketJson = JSONObject.parseObject(ticketObj.toString());
                Ticket ticket = JSON.toJavaObject(ticketJson, Ticket.class);
                Timestamp recoverTime = ticket.getRecoverTime();
                long expire = recoverTime.getTime();
                long now = System.currentTimeMillis();
                if (now > expire) {
                    return JsonResponseBuilder.buildFail(SSOContants.MSG_TICKET_TIME_OVER);
                }
                boolean isLogin = redisCacheDao.hasKey(ssoProperties.getWholeCacheName(), decodedTicket);
                if (isLogin) {
                    return JsonResponseBuilder.buildSuccess(SSOContants.MSG_CHECK_TICKET_SUCCESS);
                }
            } else {
                return JsonResponseBuilder.buildFail(SSOContants.MSG_TICKET_NOT_EXITS);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonResponseBuilder.buildFail(SSOContants.MSG_CHECK_TICKET_FAIL);
    }

    /**
     * 设置cookie
     *
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = "/setCookie")
    public Object setCookie(HttpServletRequest request, HttpServletResponse response, Model model) {
        String encodedTicket = request.getParameter(SSOContants.TICKET);
        String gotoURL = request.getParameter(SSOContants.REDIRECT_URL);
        String expiry = request.getParameter(SSOContants.EXPIRY);
        try {
            if (encodedTicket == null) {
                model.addAttribute(BaseConstant.MSG, SSOContants.MSG_NO_TICKET);
                return SSOContants.PATH.PAGE_401.getValue();
            }
            if (gotoURL == null) {
                model.addAttribute(BaseConstant.MSG, SSOContants.MSG_NO_GOTO_URL);
                return SSOContants.PATH.PAGE_401.getValue();
            }
            String decodedTicket = DESUtils.decrypt(encodedTicket, ssoProperties.getSecretKey());
            if (!redisCacheDao.hasKey(ssoProperties.getSsoTicketsCacheName(), decodedTicket)) {
                model.addAttribute(BaseConstant.MSG, SSOContants.MSG_NOT_LOGIN);
                return SSOContants.PATH.PAGE_401.getValue();
            }
            boolean isLogin = redisCacheDao.hasKey(ssoProperties.getWholeCacheName(), decodedTicket);
            if (isLogin) {
                int expireInt = ssoProperties.getTicketTimeout();
                if (StringUtils.isNotBlank(expiry)) {
                    expireInt = Integer.parseInt(expiry);
                }
                CookieUtils.createCookie(response, CookieConstant.WHOLE_COOKIE_NAME, encodedTicket, expireInt, CookieUtils.secure);
                String gotoURLDecoded = DESUtils.decrypt(gotoURL, ssoProperties.getSecretKey());
                response.sendRedirect(gotoURLDecoded);
            }
        } catch (Exception e) {
            logger.error("SSOLoginController setCookie 设置cookie失败:" + e.getMessage());
        }
        model.addAttribute(BaseConstant.MSG, SSOContants.MSG_SET_COOKIE_FAIL);
        return SSOContants.PATH.PAGE_401.getValue();
    }

    /**
     * 修改密码(参数DESUtils加密)
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/changePassword")
    public Object changePassword(HttpServletRequest request, HttpServletResponse response) {
        //登陆的票据（DESUtils加密）
        String cookieNameEncrypt = request.getParameter(SSOContants.TICKET);
        //用户名（DESUtils加密）
        String usernameEncrypt = request.getParameter(SSOContants.USER_NAME);
        //旧密码（DESUtils加密）
        String oldPasswordEncrypt = request.getParameter(SSOContants.PASSWORD);
        //新密码（DESUtils加密）
        String newPasswordEncrypt = request.getParameter(SSOContants.NEW_PASSWORD);
        try {
            //通过ticket验证是否登录
            if (null == cookieNameEncrypt || StringUtils.isBlank(cookieNameEncrypt)) {
                return JsonResponseBuilder.buildFail(SysUserConstants.NOT_LOGIN_OR_EXPIRE);
            }
            String decodedTicket = DESUtils.decrypt(cookieNameEncrypt, ssoProperties.getSecretKey());
            if (!redisCacheDao.hasKey(ssoProperties.getSsoTicketsCacheName(), decodedTicket)) {
                return JsonResponseBuilder.buildFail(SysUserConstants.NOT_LOGIN_OR_EXPIRE);
            }
            if (StringUtils.isBlank(usernameEncrypt)) {
                return JsonResponseBuilder.buildFail(SysUserConstants.LOGIN_NO_USER_NAME);
            }
            if (StringUtils.isBlank(oldPasswordEncrypt)) {
                return JsonResponseBuilder.buildFail(SysUserConstants.CHANGE_PASSWORD_FAIL_NO_OLD_PASSWORD);
            }
            if (StringUtils.isBlank(newPasswordEncrypt)) {
                return JsonResponseBuilder.buildFail(SysUserConstants.CHANGE_PASSWORD_FAIL_NO_NEW_PASSWORD);
            }
            if (oldPasswordEncrypt.equals(newPasswordEncrypt)) {
                return JsonResponseBuilder.buildFail(SysUserConstants.CHANGE_PASSWORD_FAIL_OLD_NEW_SAME);
            }
            String oldPassword = DESUtils.decrypt(oldPasswordEncrypt, ssoProperties.getSecretKey());
            String newPassword = DESUtils.decrypt(newPasswordEncrypt, ssoProperties.getSecretKey());
            String username = DESUtils.decrypt(usernameEncrypt, ssoProperties.getSecretKey());
            SysUserVo userVo = sysUserService.login(username, DigestUtils.md5Hex(oldPassword), null);
            //旧密码错误
            if (null == userVo) {
                return JsonResponseBuilder.buildFail(SysUserConstants.CHANGE_PASSWORD_FAIL_OLD_PASSWORD_ERROR);
            }
            //新密码格式错误
            if (!SysUserValidator.isPassword(newPassword)) {
                return JsonResponseBuilder.buildFail(SysUserConstants.VALIDATE_PASSWORD_ERROR);
            }
            int row = sysUserService.changePassword(userVo.getUserId(), DigestUtils.md5Hex(newPassword));
            if (row == 1) {
                // redis缓存中添加ticketKey对应用戶信息(用戶名，权限等)
                redisCacheDao.deleteByKey(ssoProperties.getWholeCacheName(), decodedTicket);
                SessionUtils.invalidate(request, response);
                logger.info("用户【" + username + "】于" + DateUtils.format(new Date()) + "修改密码成功");
                return JsonResponseBuilder.buildSuccess(SysUserConstants.CHANGE_PASSWORD_SUCCESS);
            }
        } catch (Exception e) {
            logger.error("SSOLoginController changePassword 修改密码失败:" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(SysUserConstants.CHANGE_PASSWORD_FAIL);
    }

    /**
     * 退出
     *
     * @param request  请求
     * @param response 响应
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/logout")
    public Object logout(HttpServletRequest request, HttpServletResponse response) {
        try {
            String encodedTicket = request.getParameter(SSOContants.TICKET);
            String platformTag = request.getParameter(SSOContants.PLATFORM_TAG);
            String result = SysUserConstants.LOGOUT_SUCCESS;
            if (null == ssoProperties) {
                ssoProperties = (SSOProperties) SpringContextUtil.getBean("ssoProperties");
            }
            if (StringUtils.isNotBlank(platformTag) && ssoProperties.getSystemSignPortal().equals(platformTag)) {
                //统一账户系统
                encodedTicket = CookieUtils.getCookieValueByName(request, CookieConstant.WHOLE_COOKIE_NAME);
                result = SSOUtils.createPortalLoginUrl(ssoProperties, SSOContants.PATH.PORTAL_METHOD_INDEX.getValue());
                if (null == encodedTicket) {
                    SessionUtils.invalidate(request, response);
                    return JsonResponseBuilder.buildSuccess(result);
                }
            }
            if (StringUtils.isBlank(encodedTicket)) {
                return JsonResponseBuilder.buildFail(SSOContants.MSG_NO_TICKET);
            }
            //清除session 和 cookie, redis中的用户信息
            String decodedTicket = DESUtils.decrypt(encodedTicket, ssoProperties.getSecretKey());
            redisCacheDao.deleteByKey(ssoProperties.getSsoTicketsCacheName(), decodedTicket);
            redisCacheDao.deleteByKey(ssoProperties.getWholeCacheName(), decodedTicket);
            SessionUtils.invalidate(request, response);
            return JsonResponseBuilder.buildSuccess(result);
        } catch (Exception e) {
            logger.error("SSOLoginController logout sso退出失败:" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(SysUserConstants.LOGOUT_FAIL);
    }

    /**
     * 表单登录
     *
     * @param username     用户名
     * @param password     密码(MD5加密)
     * @param captcha      验证码
     * @param gotoURL      回调地址
     * @param setCookieURL 回调设置cookie地址
     * @param platformTag  系统标志
     * @param request      请求
     * @return
     */
    @RequestMapping(value = "/formLogin", method = RequestMethod.POST)
    @ResponseBody
    public Object formLogin(String username, String password, String captcha, String gotoURL, String setCookieURL, String platformTag,
                            HttpServletRequest request) {
        try {
            long start = System.currentTimeMillis();
            if (null != captcha && !CaptchaHelper.validate(request, captcha)) {
                return JsonResponseBuilder.buildFail(SysUserConstants.LOGIN_VERIFICATION_ERROR);
            }
            if (StringUtils.isBlank(username)) {
                return JsonResponseBuilder.buildFail(SysUserConstants.LOGIN_NO_USER_NAME);
            }
            if (!SysUserValidator.isUsername(username)) {
                return JsonResponseBuilder.buildFail(SysUserConstants.LOGIN_USER_NAME_ERROR);
            }
            if (StringUtils.isBlank(password)) {
                return JsonResponseBuilder.buildFail(SysUserConstants.LOGIN_NO_PASSWORD);
            }
            if (!SysUserValidator.isPassword(password)) {
                return JsonResponseBuilder.buildFail(SysUserConstants.LOGIN_PASSWORD_ERROR);
            }
            if (StringUtils.isBlank(gotoURL)) {
                return JsonResponseBuilder.buildFail(SysUserConstants.LOGIN_FAIL_NO_REDIRECT_URL);
            }
            if (StringUtils.isBlank(platformTag)) {
                return JsonResponseBuilder.buildFail(SysUserConstants.LOGIN_NO_SYSTEM);
            }
            //验证系统标志是否正确
            List<SysAuthority> systemList = sysAuthorityService.listSystem();
            boolean isSystemRight = false;
            for (SysAuthority aSystemList : systemList) {
                if (aSystemList.getSign().equals(platformTag)) {
                    isSystemRight = true;
                    break;
                }
            }
            if (!isSystemRight) {
                return JsonResponseBuilder.buildFail(SysUserConstants.LOGIN_SYSTEM_ERROR);
            }
            if (StringUtils.isBlank(setCookieURL)) {
                return JsonResponseBuilder.buildFail(SysUserConstants.LOGIN_FAIL_NO_SETCOOKIE_URL);
            }
            //登录
            long loginStart = System.currentTimeMillis();
            SysUser loginUserByUserName = sysUserService.login(username, null);
            if (null == loginUserByUserName) {
                return JsonResponseBuilder.buildFail(SysUserConstants.LOGIN_USER_NAME_ERROR);
            }
            SysUser loginUser = sysUserService.login(username, password);
            if (null == loginUser || loginUser.getUserId() == 0) {
                return JsonResponseBuilder.buildFail(SysUserConstants.LOGIN_PASSWORD_ERROR);
            }
            long loginEnd = System.currentTimeMillis();
            logger.info("用户[" + username + "]登录耗时：" + (loginEnd - loginStart) + "ms");
            //被锁定（停用）
            if (SysUserConstants.STATUS_DISABLE.equals(loginUser.getAble())) {
                return JsonResponseBuilder.buildFail(SysUserConstants.LOGIN_FAIL_USER_LOCKED);
            }
            //根据用户系统查询用户在该系统下的所有权限
            long getUserInfoStart = System.currentTimeMillis();
            JSONObject userInfo = sysAuthorityService.getAuthorityByUser(loginUser.getUserId());
            long getUserInfoEnd = System.currentTimeMillis();
            logger.info("获取用户[" + username + "]权限信息耗时：" + (getUserInfoEnd - getUserInfoStart) + "ms");
            JSONObject systemInfo = userInfo.getJSONObject(platformTag);
            if (null == systemInfo) {
                //用户在该系统没有登录权限
                return JsonResponseBuilder.buildFail(SysUserConstants.LOGIN_FAIL_NO_AUTHRITY_IN_SYSTEM);
            }
            JSONObject userJson = new JSONObject();
            userJson.put(SSOContants.USER_NAME, loginUser.getUserName());
            userJson.put(SSOContants.REAL_NAME, loginUser.getRealName());
            userJson.put(SSOContants.UID, loginUser.getUserId());
            userInfo.put(SSOContants.USER, userJson);
            //设置过期时间: 系统当前毫秒 + 过期毫秒
            userInfo.put(SSOContants.EXPIRY, System.currentTimeMillis() + ssoProperties.getTicketTimeout() * 1000);
            //自动登录
            String[] checks = request.getParameterValues("autoAuth");
            //过期时间（秒）-默认1小时
            int expiry = ssoProperties.getTicketTimeout();
            if (checks != null && SSOContants.AUTO_AUTH.equals(checks[0])) {
                expiry = ssoProperties.getTicketTimeoutNever();
            }
            //获取cookie中的token
            String ticketKey = UUIDUtils.getUUIDString();
            String encodedTicketKey = DESUtils.encrypt(ticketKey, ssoProperties.getSecretKey());
            // redis缓存中添加ticketKey对应用戶信息(用戶名，权限等)
            long redisStart = System.currentTimeMillis();
            redisCacheDao.putCache(ssoProperties.getWholeCacheName(), ticketKey, userInfo);
            SessionUtils.setSessionUser(request, loginUser);
            SessionUtils.setSessionPermission(request, userInfo);
            Timestamp createTime = new Timestamp(System.currentTimeMillis());
            Timestamp recoverTime = SSOUtils.createRecoverTime(createTime, ssoProperties.getTicketTimeout());
            Ticket ticket = new Ticket(username, createTime, recoverTime);
            if (!redisCacheDao.hasKey(ssoProperties.getSsoTicketsCacheName(), ticketKey)) {
                redisCacheDao.putCache(ssoProperties.getSsoTicketsCacheName(), ticketKey, JSONObject.toJSONString(ticket));
            }
            long redisEnd = System.currentTimeMillis();
            logger.info("用户[" + username + "]登录信息存入redis耗时：" + (redisEnd - redisStart) + "ms");
            // 其他系统
            String setCookieURLDecoded = DESUtils.decrypt(setCookieURL, ssoProperties.getSecretKey());
            String newRedirectURL = setCookieURLDecoded + "?gotoURL=" + gotoURL + "&ticket=" + encodedTicketKey + "&expiry=" + expiry;
            long end = System.currentTimeMillis();
            logger.info("用户[" + username + "]于" + DateUtils.format(new Date()) + "登录成功，总共耗时:" + (end - start) + "ms");
            return JsonResponseBuilder.buildSuccess(BaseConstant.CODE_SUCCESS, SysUserConstants.LOGIN_SUCCESS, newRedirectURL);
        } catch (Exception e) {
            logger.error("SSOLoginController formLogin sso单点表单登录失败:" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(SysUserConstants.LOGIN_FAIL);
    }

    /**
     * 获取统一账户系统登录的用户信息
     *
     * @return
     */
    @RequestMapping("getAuthInfo")
    @ResponseBody
    public Object getAuthInfo(HttpServletRequest request) {
        try {
            //从本地session取用户登录信息
            JSONObject allInfo = SessionUtils.getSessionPermission(request);
            if (null == allInfo) {
                //本地没有session信息，从redis取用户登录信息
                String ticketEncrypt = CookieUtils.getCookieValueByName(request, CookieConstant.WHOLE_COOKIE_NAME);
                String decodedTicket = DESUtils.decrypt(ticketEncrypt, ssoProperties.getSecretKey());
                Object ticketObj = redisCacheDao.getCache(ssoProperties.getSsoTicketsCacheName(), decodedTicket);
                if (null == ticketObj) {
                    return JsonResponseBuilder.buildFail(SysUserConstants.NOT_LOGIN_OR_EXPIRE);
                }
                JSONObject ticket = JSONObject.parseObject(ticketObj.toString());
                //根据用户系统查询用户在该系统下的所有权限
                Object userName = ticket.get(SSOContants.USER_NAME);
                if (null == userName) {
                    return JsonResponseBuilder.buildFail(SysUserConstants.NOT_LOGIN_OR_EXPIRE);
                }
                SysUser userVo = sysUserService.getByUsername(userName.toString());
                if (null == userVo) {
                    return JsonResponseBuilder.buildFail(SysUserConstants.VALIDATE_USER_NOT_EXITS);
                }
                allInfo = sysAuthorityService.getAuthorityByUser(userVo.getUserId());
                if (null == allInfo) {
                    return JsonResponseBuilder.buildSuccess(new JSONObject());
                }
                JSONObject userJson = new JSONObject();
                userJson.put(SSOContants.USER_NAME, userVo.getUserName());
                userJson.put(SSOContants.REAL_NAME, userVo.getRealName());
                userJson.put(SSOContants.UID, userVo.getUserId());
                allInfo.put(SSOContants.USER, userJson);
                // redis缓存中添加ticketKey对应用戶信息(用戶名，权限等)
                redisCacheDao.deleteByKey(ssoProperties.getWholeCacheName(), decodedTicket);
                redisCacheDao.putCache(ssoProperties.getWholeCacheName(), decodedTicket, allInfo);
                SessionUtils.setSessionUser(request, userVo);
                SessionUtils.setSessionPermission(request, allInfo);
            }
            Object portalInfo = allInfo.get(ssoProperties.getSystemSignPortal());
            if (null != portalInfo && portalInfo instanceof JSONObject) {
                JSONObject portalInfoJson = (JSONObject) portalInfo;
                JSONObject loginUser = (JSONObject) allInfo.get(SSOContants.USER);
                if (null == loginUser) {
                    return JsonResponseBuilder.buildSuccess(portalInfo);
                }
                JSONObject sysUser = new JSONObject();
                sysUser.put(SSOContants.USER_NAME, loginUser.get(SSOContants.USER_NAME));
                sysUser.put(SSOContants.REAL_NAME, loginUser.get(SSOContants.REAL_NAME));
                portalInfoJson.put(SSOContants.USER, sysUser);
                request.setAttribute(SSOContants.USER_NAME, loginUser.get(SSOContants.USER_NAME));
                return JsonResponseBuilder.buildSuccess(portalInfoJson);
            }
            return JsonResponseBuilder.buildFail(HttpStatus.FORBIDDEN.value(), SSOContants.MSG_NO_AUTHORITY, null);
        } catch (Exception e) {
            logger.error("SSOLoginController getAuthInfo 统一账户管理系统获取登录用户信息失败:" + e.getMessage());
        }
        return JsonResponseBuilder.buildFail(SSOContants.MSG_GET_LOGIN_USER_INFO_ERROR);
    }
}